package com.ljm.utils;


import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.FilterChain;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/*
* 返回前端工具类
* */
public class ResponseUtil {

  //  public static void out(HttpServletResponse response, R r) throws IOException {
//        ObjectMapper mapper = new ObjectMapper();
//        ///响应 状态 + 格式
//        response.setStatus(HttpStatus.OK.value());//APPLICATION_JSON_UTF8_VALUE
// response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
//   response.setContentType("text/html;charset=utf-8");
//
//        System.out.println("getWriter  "+response.getWriter());
//        try {
//            System.out.println("getWriter  try 出错");
//            System.out.println("getWriter  try 出错"+r);
//            mapper.writeValue(response.getWriter(), r);
//        } catch (IOException e) {
//            System.out.println("ResponseUtil  try 出错");
//            e.printStackTrace();
//        }
//    PrintWriter out=response.getWriter();
//        out.println(r);
//        out.flush();
//        out.close();
//    }
    public static void out(HttpServletResponse response, R r) {
        ObjectMapper mapper = new ObjectMapper();
        response.setStatus(HttpStatus.OK.value());
       // response.setContentType("application/json;charset=UTF-8");
       // response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        try {

//            PrintWriter printWriter = response.getWriter();
//            mapper.writeValue(printWriter, r);
//           // printWriter.println(r);
//            printWriter.flush();
//            printWriter.close();




        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();

//        // 生成jwt，并放置到请求头中
//        //String jwt = jwtUtils.generateToken(authentication.getName());
//            Object token = r.getData().get("token");
//            response.setHeader("token", (String) token);

        //R result = Result.succ("");

        outputStream.write(JSONUtil.toJsonStr(r).getBytes("UTF-8"));
            outputStream.flush();
            outputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }



    }


//    public static void write(HttpServletResponse response,Object o)throws Exception{
//        response.setContentType("text/html;charset=utf-8");
//        PrintWriter out=response.getWriter();
//        out.println(o.toString());
//        out.flush();
//        out.close();
//    }

}
